<template>
  <vxe-modal :id="'addForm_'+id" v-model="showDialog" :title="dialogTitle" :before-close="handleClose" width="700"
    show-footer show-zoom resize remember storage>
    <template #default>
      <el-form ref="form" :rules="rules" size="small" :model="form" label-width="100px">
        <el-row :gutter="4">
          <template v-for="item in columns">
            <el-col v-if="item.is_add" :key="item.id" :span="Number(item.span)">
              <el-form-item :label="item.cn" :prop="item.en" :label-width="item.form_label_width">
                <el-input v-if="item.type == 'input'" v-model="form[item.en]" @input="fieldChange(item.on_change)"
                  :placeholder="item.placeholder" />
                <el-select v-if="item.type == 'select'" v-model="form[item.en]" style="width: 100%;" filterable
                  placeholder="请选择" @change="fieldChange(item.on_change)">
                  <el-option v-for="selectItem in selectDatas[item.en]" :key="selectItem.id" :label="selectItem.label"
                    :value="selectItem.value" />
                </el-select>
                <el-input v-if="item.type == 'selector'" v-model="form[item.en + '_show_value']" :readonly="true"
                  :placeholder="item.placeholder">
                  <template slot="prepend">
                    <el-button style="color:#66B1FF" icon="el-icon-s-grid"
                      @click="selectorShow(item)">{{ form[item.en] }}</el-button>
                  </template>
                  <template slot="append">
                    <el-button style="color:red" icon="el-icon-circle-close" circle @click="clearSelector(item.en)" />
                  </template>
                </el-input>
                <el-input v-if="item.type == 'user'" v-model="form[item.en + '_show_value']" :readonly="true"
                  :placeholder="item.placeholder">
                  <template slot="prepend">
                    <el-button style="color:#66B1FF" icon="el-icon-s-grid"
                      @click="selectUserShow(item)">{{ form[item.en] }}</el-button>
                  </template>
                  <template slot="append">
                    <el-button style="color:red" icon="el-icon-circle-close" circle @click="clearSelector(item.en)" />
                  </template>
                </el-input>
                <el-radio-group v-if="item.type == 'radio'" v-model="form[item.en]"
                  @change="fieldChange(item.on_change)">
                  <el-radio v-for="selectItem in selectDatas[item.en]" :key="selectItem.id"
                    :label="selectItem.value">{{ selectItem.label }}</el-radio>
                </el-radio-group>
                <el-switch v-if="item.type == 'switch'" v-model="form[item.en]" active-color="#13ce66"
                  inactive-color="#ff4949" @change="fieldChange(item.on_change)" />
                <el-date-picker v-if="item.type == 'date'" v-model="form[item.en]" type="date" value-format="yyyy-MM-dd"
                  style="width: 100%;" placeholder="选择日期" @change="fieldChange(item.on_change)" />
                <el-date-picker v-if="item.type == 'datetime'" v-model="form[item.en]" type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" placeholder="选择日期"
                  @change="fieldChange(item.on_change)" />
                <el-button v-if="item.type=='file'" @click="fileShow(item)">查看</el-button>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
        <slot name="add_form_append" :form="form" />
      </el-form>
      <selector ref="selectorDialog" @confirm="selectorConfirm" />
      <File ref="fileList" @fileModify="fileModify" />
    </template>
    <template #footer>
      <el-button type="primary" :loading="confirmStatu" @click="onSubmit">{{ confirmText }}</el-button>
    </template>
  </vxe-modal>
</template>

<script>
  var _this = this;
  import Selector from './selector.vue'
  import {
    new_
  } from '@/api/template/index'
  import File from '@/views/template/components/file.vue'

  export default {
    components: {
      File,
      Selector
    },
    props: {
      add_method: {
        type: String
      }
    },
    data() {
      return {
        showDialog: false,
        id: 'id',
        data_object: {},
        columns: null,
        selectDatas: null,
        rules: null,
        form: {},
        precondition: {},
        fileList: [],
        dialogTitle: '新增',
        selectRow: [],
        confirmStatu: false,
        confirmText: '确  定',
        interceptorConfirm: false,
      }
    },
    methods: {
      show(params) {
        this.showDialog = true
        const {
          id,
          columns,
          headrow,
          selectDatas,
          rules,
          data_object,
          precondition
        } = params
        this.id = id
        this.columns = columns
        this.headrow = headrow
        this.selectDatas = selectDatas
        this.rules = rules
        this.data_object = data_object
        this.precondition = precondition
        this.form = {}
        for (var i = 0; i < columns.length; i++) {
          if (columns[i].type === 'switch') {
            this.$set(this.form, columns[i].en, false)
          }
        }
        this.$nextTick(() => {
          this.$parent.$emit('addInit', {
            form: this.form
          })
        })
      },
      fieldChange(code) {
        eval(code)
      },
      onSubmit() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.confirmStatu = true
            this.confirmText = '提交中'
            var submitForm = JSON.parse(JSON.stringify(this.form))
            for (const key in this.precondition) {
              this.$set(submitForm, key, this.precondition[key])
            }
            new_({
                form: submitForm,
                fileList: this.fileList,
                data_object_no: this.data_object.no,
                interceptorConfirm: this.interceptorConfirm
              })
              .then(res => {
                if (res.type === 'confirm') {
                  this.$confirm(res.msg, '提示', {
                    confirmButtonText: res.confirmButton,
                    cancelButtonText: res.cancelButton,
                    type: 'warning'
                  }).then(() => {
                    this.interceptorConfirm = true
                    this.onSubmit('form')
                  })
                } else {
                  this.$message({
                    message: res.msg,
                    type: 'success'
                  })
                  if (!this.data_object.is_save_add) {
                    this.form = {}
                  }
                  this.interceptorConfirm = false
                  this.close()
                  this.$emit('success', res.newData)
                }
              })
              .finally(e => {
                this.confirmStatu = false
                this.confirmText = '确  定'
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      selectorShow(item) {
        this.$refs.selectorDialog.show(item, 2, this.headrow, this.form)
      },
      selectorConfirm({
        item,
        rows
      }) {
        const selectRow = rows
        this.selectRow = selectRow
        var en = ''
        var en_show_value = ''
        for (var i = 0; i < selectRow.length; i++) {
          en += selectRow[i][JSON.parse(item.type_config).key] + ','
          en_show_value += selectRow[i][JSON.parse(item.type_config).value] + ','
        }
        this.$set(this.form, item.en, en.substring(0, en.length - 1))
        this.$set(this.form, item.en + '_show_value', en_show_value.substring(0, en_show_value.length - 1))
        this.$refs.form.clearValidate()
        this.fieldChange(item.on_change)
      },
      clearSelector(en) {
        this.$delete(this.form, en)
        this.$delete(this.form, en + '_show_value')
      },
      selectUserShow(item) {
        var config = JSON.parse(item.type_config)
        if (this.form[item.en] != null) {
          config.select_userids = this.form[item.en].split(',')
        }
        this.$UserSelector.show(config).then(res => {
          var userids = ''
          var usernames = ''
          for (var i = 0; i < res.length; i++) {
            userids += res[i].userid + ','
            usernames += res[i].username + ','
          }
          this.$set(this.form, item.en, userids.substring(0, userids.length - 1))
          this.$set(this.form, item.en + '_show_value', usernames.substring(0, usernames.length - 1))
        })
      },
      fileShow(item) {
        var file_edit = true
        if (item.update_validate != null) {
          var auth = JSON.parse(item.update_validate)
          for (var j = 0; j < auth.length; j++) {
            for (const key in this.row) {
              if (key === auth[j].field) {
                var aaa = this.row[key] + auth[j].operator + auth[j].value
                if (!eval(aaa)) {
                  file_edit = false
                }
              }
            }
          }
        }
        this.fileItem = item
        this.$refs.fileList.show({
          ids: this.form[item.en],
          title: item.cn + '列表',
          accpetTypes: item.type_config.split('|')[2],
          limit: item.type_config.split('|')[1],
          folder: item.type_config.split('|')[0],
          file_edit: true
        })
      },
      fileModify(fileIds) {
        this.form[this.fileItem.en] = fileIds
      },
      beforeRemove(file, fileList) {
        this.fileList = fileList
      },
      handleSuccess(res, file, fileList) {
        this.fileList = fileList
      },
      handleExceed(file, fileList) {
        this.$message({
          type: 'error',
          message: '超出文件个数限制'
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.form = {}
            this.fileList = []
            this.showDialog = false
          })
          .catch(_ => {})
      },
      close() {
        this.fileList = []
        this.showDialog = false
      }
    }
  }
</script>
